//
//  SearchViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/7/31.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit

class SearchViewController: BaseViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchField: UITextField!
    @IBOutlet weak var navHeight: NSLayoutConstraint!
    
    var searchTblHeader:UIView?
    
    var hitstoryArray = [String]() // 搜索历史
    var hotSearchArray = [HotSearchValueModel]() // 热门搜索
    
    var searchString = "" // 搜索的关键字
    var searchValue = [String]()
    var searchKeyBoard = [String]()
    
    lazy var searchTabelView:UITableView = {
        let tblView = UITableView.init(frame: CGRect.init(x: 0, y: Utils.isIphoneX() ? 88 : 64, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight - CGFloat(Utils.isIphoneX() ? 88 : 64)), style: .plain)
        tblView.delegate = self
        tblView.dataSource = self
        tblView.separatorColor = UIColor.viewLineColor
        tblView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        tblView.isHidden = true
        tblView.rowHeight = 45
        tblView.tableFooterView = UIView()
        tblView.register(UINib.init(nibName: "SearchValueTableViewCell", bundle: nil), forCellReuseIdentifier: "SearchValueTableViewCell")
        return tblView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 130
        self.tableView.backgroundColor = UIColor.nav_color
        self.tableView.tableFooterView = UIView()
        self.searchField.addTarget(self, action: #selector(valueChange(sender:)), for: .editingChanged)
        self.view.addSubview(self.searchTabelView)
        if Utils.isIphoneX() {
            self.navHeight.constant = 88
        }
        
        Utils.setTextFieldPlaceholderColor(textField: self.searchField)
        
        self.allRequest()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    func allRequest(){
        PKhud.show()
        let semaphore = DispatchSemaphore.init(value: 0)
        let group = DispatchGroup.init()
        let queue = DispatchQueue.global()
        
        queue.async(group: group) {
            self.getPlistData {
                semaphore.signal()
            }
        }
        
        queue.async(group: group) {
            self.getHotSearch  {
                semaphore.signal()
            }
        }
        
        
        
        group.notify(queue: queue) {
            semaphore.wait()
            semaphore.wait()
            
            DispatchQueue.main.async {
                PKhud.hiden()
                self.tableView.reloadData()
            }
        }
    }
    
    // MARK:获取搜索历史记录
    func getPlistData(closure:@escaping ()->()){
        let filePath:String = NSHomeDirectory() + "/Documents/Searchhistory.plist"
        let hotArr = NSArray.init(contentsOfFile: filePath)
        guard hotArr != nil else {
            closure()
            return
        }
        self.hitstoryArray = self.hitstoryArray + (hotArr as! [String])
        closure()
    }
    
    // MARK:获取热搜
    func getHotSearch(closure:@escaping ()->()){
        
        HttpRequest.requestData(.post, URLString: Api.hot_search.rawValue, parameters:nil ) { (result) in
            if result["msg"] as! String == "success"{
                if let array = [HotSearchValueModel].deserialize(from: result["data"] as? [Any]) as? [HotSearchValueModel]{
                    self.hotSearchArray = array
                    closure()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
        
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func backMethod(_ sender: UIButton) {
        self.backBarButtonMethon()
    }
    
    // MARK:搜索
    @IBAction func searchMethod(_ sender: UIButton) {
        
        if self.searchKeyBoard.count == 0  {
            return
        }
        let str = self.searchField.text!.trimmingCharacters(in: .whitespaces) // 去掉首位空格
        guard str != "" else {
            return
        }
        if !self.hitstoryArray.contains(str){
            self.hitstoryArray.append(str)
        }
        self.tableView.reloadData()
        Utils.saveSearchHistory(array: self.hitstoryArray)
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "SearchDetailViewController") as! SearchDetailViewController
        ctrl.keyword = str
        ctrl.backSearchValue = { [weak self] (value) in
            let str = value.trimmingCharacters(in: .whitespaces) // 去掉首位空格
            if !(self?.hitstoryArray.contains(str))!{
                self?.hitstoryArray.append(str)
                Utils.saveSearchHistory(array: (self?.hitstoryArray)!)
                self?.tableView.reloadData()
            }
            
        }
        self.navigationController?.pushViewController(ctrl, animated: true)
    }

}


extension SearchViewController:UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        var count = 0
        if self.hotSearchArray.count != 0 {
            count = count + 1
        }
        if self.hitstoryArray.count != 0 {
            count = count + 1
        }
        return tableView == self.tableView ? count : 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableView == self.tableView ? 1 : self.searchKeyBoard.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView == self.tableView {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SearchTableViewCell") as! SearchTableViewCell
            if indexPath.section == 0 && self.hotSearchArray.count != 0 {
                cell.titleLabel.text = "热门搜索"
                cell.clearButton.isHidden = true
                cell.updateCollectionViewHeight(array: self.hotSearchArray)
            }else{
                cell.titleLabel.text = "历史搜索"
                cell.clearButton.isHidden = false
                cell.updateCollectionViewHeight(array: self.hitstoryArray)
            }
            cell.clearClosure = { [weak self] in
                self?.removeHistory()
            }
            
            cell.backSeleValue = { [weak self] (value ) in
                let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "SearchDetailViewController") as! SearchDetailViewController
                ctrl.keyword = value
                self?.navigationController?.pushViewController(ctrl, animated: true)
            }
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "SearchValueTableViewCell") as! SearchValueTableViewCell
            cell.selectionStyle = .none
            cell.reload(withkeyBoard: self.searchKeyBoard[indexPath.row], searchValue: self.searchField.text!)
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView == self.searchTabelView {
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "SearchDetailViewController") as! SearchDetailViewController
            ctrl.keyword = self.searchKeyBoard[indexPath.row]
            self.navigationController?.pushViewController(ctrl, animated: true)
        }
    }
    
    func removeHistory(){
        self.hitstoryArray.removeAll()
        Utils.saveSearchHistory(array: self.hitstoryArray)
        self.tableView.reloadData()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if tableView == self.tableView {
            if section == 1 {
                let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 10))
                header.backgroundColor = UIColor.backgroundColor
                return header
            }
            return UIView()
        }else{
            return UIView()
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if tableView == self.tableView {
            return section == 0 ? 0 : 10
        } 
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    
    // MARK:发布新需求
    @objc func btnClick(){
        
        guard Utils.isLogined() else {
            PKhud.showText(text: "请先登录~")
            Utils.goLoginCtrol(ctrl: self, isHidenBottomBar: false)
            return
        }
        
        // 新品需求
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "NewGoodsDemandViewController") as! NewGoodsDemandViewController
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    // MARK:搜索词改变
    @objc func valueChange(sender:UITextField){
        if sender.text?.count != 0 {
            self.searchTabelView.isHidden = false
        }else{
            self.searchTabelView.isHidden = true
            return
        }
        
        HttpRequest.requestData(.post, URLString: Api.keyword.rawValue, parameters: ["name":self.searchField.text!]) { (result) in
            if result["msg"] as! String == "success"{
                if let array = result["data"] as? [String] {
                    self.searchKeyBoard.removeAll()
                    self.searchKeyBoard = array
                    self.searchTabelView.reloadData()
                    self.searchTabelView.bounces = array.count == 0 ? true : false
                    if array.count == 0 {
                        self.initSearchTblHeader()
                    }else{
                        self.searchTabelView.tableHeaderView = nil
                    }
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    func initSearchTblHeader(){
        if self.searchTblHeader == nil {
            let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 180))
            header.backgroundColor = UIColor.white
            let label = Utils.labelWith(frame: CGRect.init(x: 24, y: 29, width: UIScreen.ScreenWidth - 48, height: 38), font: UIFont.systemFont(ofSize: 14), textAlignment: .center, textColor: "#999999", text: "sorry，没有符合的搜索结果，您可以发布一个新需求我们将尽快为您铺货")
            label.numberOfLines = 0
            header.addSubview(label)
            let btn = UIButton.init(type: .custom)
            btn.frame = CGRect.init(x: UIScreen.ScreenWidth/2-209/2, y: label.bottom + 15, width: 209, height: 49)
            btn.setBackgroundImage(UIImage.init(named: "button_1"), for: .normal)
            btn.setTitle("发布新需求", for: .normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
            btn.setTitleColor(UIColor.white, for: .normal)
            btn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 10, 0)
            btn.addTarget(self, action: #selector(btnClick), for: .touchUpInside)
            header.addSubview(btn)
            self.searchTblHeader = header
        }
        self.searchTabelView.tableHeaderView = self.searchTblHeader
        
    }
    
    
}
